<script setup>
import { ref, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { templateApi } from '@/api'
import { showToast } from 'vant'

const router = useRouter()
const route = useRoute()
const loading = ref(false)
const isEdit = ref(false)

// 表单数据
const form = ref({
  id: null,
  name: '',
  scopeType: 'SYSTEM',
  subscribeMode: 'RAW',
  dataFormat: 'CSV',
  dataSource: '日库',
  groupFields: [],
  numericAggFields: '',
  conditions: '',
  selectedFields: []
})

// 选项数据
const scopeTypeOptions = [
  { text: '系统订阅', value: 'SYSTEM' },
  { text: '各关订阅', value: 'CUSTOMS' }
]

const subscribeModeOptions = [
  { text: '原始数据', value: 'RAW' },
  { text: '汇总数据', value: 'AGG' }
]

const dataFormatOptions = [
  { text: 'CSV', value: 'CSV' },
  { text: 'TXT', value: 'TXT' },
  { text: 'EXCEL', value: 'EXCEL' },
  { text: '331格式', value: '331' }
]

const dataSourceOptions = [
  { text: '日库', value: '日库' },
  { text: '月库', value: '月库' },
  { text: '发布', value: '发布' }
]

// 字段选项（示例）
const fieldOptions = [
  { text: '报关单号', value: 'entry_id' },
  { text: '商品序号', value: 'g_no' },
  { text: '进出口标志', value: 'i_e_flag' },
  { text: '贸易方式', value: 'trade_mode' },
  { text: '运输方式', value: 'trans_mode' },
  { text: '征免性质', value: 'cut_mode' },
  { text: '商品编号', value: 'code_ts' },
  { text: '商品名称', value: 'g_name' },
  { text: '规格型号', value: 'g_model' },
  { text: '数量', value: 'qty' },
  { text: '单价', value: 'price' },
  { text: '总价', value: 'total' }
]

// 汇总字段选项
const groupFieldOptions = [
  { text: '贸易方式', value: 'trade_mode' },
  { text: '运输方式', value: 'trans_mode' },
  { text: '征免性质', value: 'cut_mode' },
  { text: '商品编号', value: 'code_ts' },
  { text: '进出口标志', value: 'i_e_flag' }
]

// 加载模板详情（编辑模式）
const loadTemplate = async () => {
  if (!route.params.id) return

  loading.value = true
  try {
    const template = await templateApi.getTemplateById(route.params.id)

    // 填充表单数据，处理字符串字段转数组
    form.value = {
      ...template,
      groupFields: template.groupFields ? template.groupFields.split(',').filter(s => s.trim()) : [],
      selectedFields: template.selectedFields ? template.selectedFields.split(',').filter(s => s.trim()) : []
    }
  } catch (error) {
    showToast('加载失败: ' + error.message)
    router.back()
  } finally {
    loading.value = false
  }
}

// 保存模板
const saveTemplate = async () => {
  // 基本验证
  if (!form.value.name.trim()) {
    showToast('请输入模板名称')
    return
  }

  loading.value = true
  try {
    await templateApi.saveTemplate(form.value)
    showToast(isEdit.value ? '更新成功' : '创建成功')
    router.back()
  } catch (error) {
    showToast('保存失败: ' + error.message)
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  isEdit.value = !!route.params.id
  if (isEdit.value) {
    loadTemplate()
  }
})
</script>

<template>
  <div class="page-container">
    <van-nav-bar
      :title="isEdit ? '编辑模板' : '新建模板'"
      left-arrow
      @click-left="router.back()"
    />

    <van-form @submit="saveTemplate">
      <van-cell-group inset>
        <van-field
          v-model="form.name"
          name="name"
          label="模板名称"
          placeholder="请输入模板名称"
          :rules="[{ required: true, message: '请输入模板名称' }]"
        />

        <van-field name="scopeType" label="范围类型">
          <template #input>
            <van-radio-group v-model="form.scopeType" direction="horizontal">
              <van-radio
                v-for="option in scopeTypeOptions"
                :key="option.value"
                :name="option.value"
              >
                {{ option.text }}
              </van-radio>
            </van-radio-group>
          </template>
        </van-field>

        <van-field name="subscribeMode" label="订阅模式">
          <template #input>
            <van-radio-group v-model="form.subscribeMode" direction="horizontal">
              <van-radio
                v-for="option in subscribeModeOptions"
                :key="option.value"
                :name="option.value"
              >
                {{ option.text }}
              </van-radio>
            </van-radio-group>
          </template>
        </van-field>

        <van-field name="dataFormat" label="数据格式">
          <template #input>
            <van-radio-group v-model="form.dataFormat" direction="horizontal">
              <van-radio
                v-for="option in dataFormatOptions"
                :key="option.value"
                :name="option.value"
              >
                {{ option.text }}
              </van-radio>
            </van-radio-group>
          </template>
        </van-field>

        <van-field name="dataSource" label="数据源">
          <template #input>
            <van-radio-group v-model="form.dataSource" direction="horizontal">
              <van-radio
                v-for="option in dataSourceOptions"
                :key="option.value"
                :name="option.value"
              >
                {{ option.text }}
              </van-radio>
            </van-radio-group>
          </template>
        </van-field>

        <!-- 汇总模式时显示汇总字段选择 -->
        <van-field
          v-if="form.subscribeMode === 'AGG'"
          name="groupFields"
          label="汇总字段"
        >
          <template #input>
            <van-checkbox-group v-model="form.groupFields">
              <van-checkbox
                v-for="option in groupFieldOptions"
                :key="option.value"
                :name="option.value"
              >
                {{ option.text }}
              </van-checkbox>
            </van-checkbox-group>
          </template>
        </van-field>

        <!-- 汇总模式时显示数值字段聚合配置 -->
        <van-field
          v-if="form.subscribeMode === 'AGG'"
          v-model="form.numericAggFields"
          name="numericAggFields"
          label="数值字段聚合"
          type="textarea"
          placeholder="请输入数值字段聚合配置（JSON格式）"
          rows="3"
        />

        <van-field name="selectedFields" label="字段选择">
          <template #input>
            <van-checkbox-group v-model="form.selectedFields">
              <van-checkbox
                v-for="option in fieldOptions"
                :key="option.value"
                :name="option.value"
              >
                {{ option.text }}
              </van-checkbox>
            </van-checkbox-group>
          </template>
        </van-field>

        <van-field
          v-model="form.conditions"
          name="conditions"
          label="统计条件"
          type="textarea"
          placeholder="请输入统计条件（JSON格式）"
          rows="3"
        />
      </van-cell-group>

      <div style="margin: 16px;">
        <van-button
          round
          block
          type="primary"
          native-type="submit"
          :loading="loading"
        >
          {{ isEdit ? '更新' : '创建' }}
        </van-button>
      </div>
    </van-form>
  </div>
</template>

<style scoped>
.van-cell-group {
  margin-bottom: 12px;
}
</style>
